package com.xvyy.tingshu.payment.api;

import com.xvyy.tingshu.common.login.annotation.TsLogin;
import com.xvyy.tingshu.common.result.Result;
import com.xvyy.tingshu.common.util.AuthContextHolder;
import com.xvyy.tingshu.payment.service.WxPayService;
import com.wechat.pay.java.service.payments.model.Transaction;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.enums.ParameterIn;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Tag(name = "微信支付接口")
@RestController
@RequestMapping("api/payment/wxPay")
@Slf4j
public class WxPayApiController {

    @Autowired
    private WxPayService wxPayService;

    //http://192.168.217.1:8500/api/payment/wxPay/createJsapi/1301/undefined
    @PostMapping("/createJsapi/{paymentType}/{orderNo}")
    @Operation(summary = "预支付下单")
    @TsLogin
    public Result<Map<String, Object>> createJsapi(@PathVariable(value = "paymentType") Long paymentType, @PathVariable(value = "orderNo")  String orderNo) {
        Map<String, Object> map = wxPayService.createJsapi(paymentType, orderNo);
        return Result.ok(map);
    }

    //http://192.168.217.1:8500/api/payment/wxPay/queryPayStatus/PQUMwHEriMpRqMf
    @GetMapping("/queryPayStatus/{orderNo}")
    @Operation(summary = "查询支付状态")
    @TsLogin
    public Result<Boolean> queryPayStatus(@PathVariable(value = "orderNo") String orderNo) {
        // 1. 查询支付状态
        Transaction transaction = wxPayService.queryPayStatus(orderNo);
        if (transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
            // 2. 该比订单钱已经支付
            wxPayService.wxPaySuccess(orderNo);
            return Result.ok(true);
        }
        // 3. 该笔订单钱未支付
        return Result.ok(false);
    }

    //http://192.168.217.1:8500/api/payment/wxPay/notifyer 内网穿透测试
    @PostMapping("/notifyer")
    @Operation(summary = "wx异步回调通知")
    public Map<Object, Object> notifyer(HttpServletRequest httpServletRequest) {
        try {
            Transaction transaction = wxPayService.notifier(httpServletRequest);
            if (transaction != null && transaction.getTradeState().equals(Transaction.TradeStateEnum.SUCCESS)) {
                String outTradeNo = transaction.getOutTradeNo();
                wxPayService.wxPaySuccess(outTradeNo);
                HashMap<Object, Object> successMap = new HashMap<>();
                successMap.put("code", "SUCCESS");
                successMap.put("message", "成功");
                return successMap;
            }
        } catch (Exception e) {
            log.error("微信验签以及解析数据失败:{}", e.getMessage());
        }
        HashMap<Object, Object> failMap = new HashMap<>();
        failMap.put("code", "FAIL");
        failMap.put("message", "失败");
        return failMap;
    }

    @TsLogin
    @Operation(summary = "微信Native下单")
    @Parameters({
            @Parameter(name = "paymentType",description = "支付类型：1301-订单 1302-充值",in = ParameterIn.PATH,required = true),
            @Parameter(name = "orderNo",description = "订单号",required = true,in = ParameterIn.PATH),
    })
    @PostMapping("/createNative/{paymentType}/{orderNo}")
    public Result<Map<String, Object>> createNative(@PathVariable String paymentType, @PathVariable String orderNo) {
        Map<String, Object> map = wxPayService.createNative(paymentType, orderNo, AuthContextHolder.getUserId());
        return Result.ok(map);
    }

}
